<template>
  <div class="app-container">
    <!-- 查询表单 -->
    <!-- 这是一条远程仓库的拉取测试 -->
    <el-form :inline="true" :model="queryParams" class="demo-form-inline">
      <el-form-item label="班级名称">
        <el-input v-model="queryParams.name" placeholder="班级名称" clearable />
      </el-form-item>
      <el-form-item label="开课时间">
        <el-date-picker
          v-model="queryParams.begin"
          type="date"
          placeholder="开始日期"
          value-format="YYYY-MM-DD"
        />
        <span style="margin: 0 10px">至</span>
        <el-date-picker
          v-model="queryParams.end"
          type="date"
          placeholder="结束日期"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleQuery">查询</el-button>
        <el-button @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <div style="margin-bottom: 20px">
      <el-button type="primary" @click="handleAdd">添加班级</el-button>
    </div>

    <!-- 数据表格 -->
    <el-table :data="clazzList" border style="width: 100%">
      <el-table-column type="index" label="序号" width="80" :index="indexMethod" header-align="center" align="center" />
      <el-table-column prop="name" label="班级名称" width="180" header-align="center" align="center" />
      <el-table-column prop="room" label="教室" width="120" header-align="center" align="center" />
      <el-table-column prop="beginDate" label="开课时间" width="120" header-align="center" align="center" />
      <el-table-column prop="endDate" label="结课时间" width="120" header-align="center" align="center" />
      <el-table-column prop="masterName" label="班主任" width="120" header-align="center" align="center" />
      <el-table-column prop="status" label="状态" width="120" header-align="center" align="center">
        <template #default="scope">
          <el-tag :type="statusTagType(scope.row.status)">
            {{ scope.row.status }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="updateTime" label="最后修改时间" width="180" header-align="center" align="center">
        <template #default="scope">
          {{ formatTime(scope.row.updateTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180" header-align="center" align="center">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="queryParams.page"
        v-model:page-size="queryParams.pageSize"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="50%"
      @close="resetForm"
    >
      <el-form ref="clazzForm" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="班级名称" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="教室" prop="room">
          <el-input v-model="form.room" />
        </el-form-item>
        <el-form-item label="开课时间" prop="beginDate">
          <el-date-picker
            v-model="form.beginDate"
            type="date"
            placeholder="选择日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="结课时间" prop="endDate">
          <el-date-picker
            v-model="form.endDate"
            type="date"
            placeholder="选择日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="班主任" prop="masterId">
          <el-select v-model="form.masterId" placeholder="请选择班主任">
            <el-option
              v-for="teacher in teacherList"
              :key="teacher.id"
              :label="teacher.name"
              :value="teacher.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="学科" prop="subject">
          <el-select v-model="form.subject" placeholder="请选择学科">
            <el-option label="Java" :value="1" />
            <el-option label="前端" :value="2" />
            <el-option label="大数据" :value="3" />
            <el-option label="Python" :value="4" />
            <el-option label="Go" :value="5" />
            <el-option label="嵌入式" :value="6" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  listClazzs,
  addClazz,
  updateClazz,
  deleteClazz,
  getClazzById,
  listAllClazzs
} from '@/api/clazz'
import { queryAllApi } from '@/api/emp'

// 查询参数
const queryParams = ref({
  name: '',
  begin: '',
  end: '',
  page: 1,
  pageSize: 10
})

// 表单数据
const form = ref({
  id: null,
  name: '',
  room: '',
  beginDate: '',
  endDate: '',
  masterId: null,
  subject: null
})

// 表单验证规则
const rules = ref({
  name: [{ required: true, message: '请输入班级名称', trigger: 'blur' }],
  room: [{ required: true, message: '请输入教室', trigger: 'blur' }],
  beginDate: [{ required: true, message: '请选择开课时间', trigger: 'change' }],
  endDate: [{ required: true, message: '请选择结课时间', trigger: 'change' }],
  masterId: [{ required: true, message: '请选择班主任', trigger: 'change' }],
  subject: [{ required: true, message: '请选择学科', trigger: 'change' }]
})

const clazzList = ref([])
const total = ref(0)
const dialogVisible = ref(false)
const dialogTitle = ref('')
const teacherList = ref([]) // 假设已获取教师列表
const clazzForm = ref(null)

// 获取班级列表
const getList = async () => {
  try {
    const res = await listClazzs(queryParams.value)
    if (res.code === 1) {
      clazzList.value = res.data.rows
      total.value = res.data.total
    }
  } catch (error) {
    console.error(error)
  }
}

// 查询
const handleQuery = () => {
  queryParams.value.page = 1
  getList()
}

// 重置查询
const resetQuery = () => {
  queryParams.value = {
    name: '',
    begin: '',
    end: '',
    page: 1,
    pageSize: 10
  }
  getList()
}

// 分页大小变化
const handleSizeChange = (val) => {
  queryParams.value.pageSize = val
  getList()
}

// 当前页变化
const handleCurrentChange = (val) => {
  queryParams.value.page = val
  getList()
}

// 添加班级
const handleAdd = () => {
  dialogTitle.value = '添加班级'
  dialogVisible.value = true
  nextTick(() => {
    clazzForm.value?.clearValidate()
  })
}

// 编辑班级
const handleEdit = async (row) => {
  try {
    const res = await getClazzById(row.id)
    if (res.code === 1) {
      form.value = { ...res.data }
      dialogTitle.value = '编辑班级'
      dialogVisible.value = true
    }
  } catch (error) {
    console.error(error)
  }
}

// 删除班级
const handleDelete = (row) => {
  ElMessageBox.confirm('确定删除该班级吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      try {
        const res = await deleteClazz(row.id)
        if (res.code === 1) {
          ElMessage.success('删除成功')
          getList()
        }
      } catch (error) {
        console.error(error)
      }
    })
    .catch(() => {
      ElMessage.info('已取消删除')
    })
}

// 提交表单
const submitForm = async () => {
  await clazzForm.value.validate()
  try {
    if (form.value.id) {
      // 编辑
      const res = await updateClazz(form.value)
      if (res.code === 1) {
        ElMessage.success('修改成功')
        dialogVisible.value = false
        getList()
      }
    } else {
      // 添加
      const res = await addClazz(form.value)
      if (res.code === 1) {
        ElMessage.success('添加成功')
        dialogVisible.value = false
        getList()
      }
    }
  } catch (error) {
    console.error(error)
  }
}

// 重置表单
const resetForm = () => {
  form.value = {
    id: null,
    name: '',
    room: '',
    beginDate: '',
    endDate: '',
    masterId: null,
    subject: null
  }
}

// 序号计算方法
const indexMethod = (index) => {
  return (queryParams.value.page - 1) * queryParams.value.pageSize + index + 1
}

// 状态标签样式
const statusTagType = (status) => {
  switch (status) {
    case '未开班':
      return 'info'
    case '已开班':
      return 'success'
    case '已结课':
      return 'warning'
    default:
      return ''
  }
}

// 格式化时间
const formatTime = (time) => {
  if (!time) return ''
  const date = new Date(time)
  return date.toLocaleString()
}

// 获取员工列表
const getTeacherList = async () => {
  try {
    const res = await queryAllApi()
    if (res.code === 1) {
      teacherList.value = res.data
    }
  } catch (error) {
    console.error(error)
  }
}

onMounted(() => {
  getList()
  getTeacherList()
})
</script>

<style scoped>
.app-container {
  padding: 24px;
  background-color: #f8fafc;
  min-height: calc(100vh - 50px);
}

.demo-form-inline {
  background: #fff;
  padding: 24px;
  border-radius: 12px;
  box-shadow: 0 4px 20px 0 rgba(0, 0, 0, 0.05);
  margin-bottom: 24px;
}

.el-table {
  margin-top: 24px;
  font-size: 14px;
  box-shadow: 0 4px 20px 0 rgba(0, 0, 0, 0.05);
  border-radius: 12px;
  overflow: hidden;
}

.el-table :deep(.el-table__cell) {
  padding: 14px 0;
}

.el-button {
  transition: all 0.3s;
  border-radius: 8px;
  padding: 10px 20px;
}

.el-button + .el-button {
  margin-left: 12px;
}

.pagination-container {
  margin-top: 24px;
  padding: 20px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 4px 20px 0 rgba(0, 0, 0, 0.05);
  text-align: center;
}

.el-dialog {
  border-radius: 16px;
}

.el-dialog__body {
  padding: 24px 24px 12px;
}

.el-form-item {
  margin-bottom: 20px;
}

.el-date-editor.el-input, 
.el-date-editor.el-input__inner {
  width: 100%;
  border-radius: 8px;
}

.el-select {
  width: 100%;
}

.el-input__inner {
  border-radius: 8px;
}

/* 过渡动画 */
.fade-enter-active,
.fade-leave-active {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}
.fade-enter-from,
.fade-leave-to {
  opacity: 0;
  transform: translateY(10px);
}
</style>
